package com.jams.goodox.activity.home;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.SparseArray;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;

import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.HomeService;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.UImageUtils;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import uama.hangzhou.image.photochoose.FourPicturesChoose;

/**
 * Created by Administrator on 2017/11/12.
 */

public class CommentActivity extends BaseActivity {
    @Bind(R.id.recycle_view)
    RecyclerView recycleView;
    RecycleCommonAdapter recycleCommonAdapter;

    private List<OrderResp.DataBean.ProductBean> productInfoList;
    private FourPicturesChoose[] fourPicturesChooseList;
    private OrderResp.DataBean orderBean;

    @Override
    protected int getLayoutId() {
        return R.layout.comment_activity;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this,"评价订单");
        orderBean = (OrderResp.DataBean) getIntent().getSerializableExtra("orderBean");
        productInfoList = orderBean.getProduct();
        fourPicturesChooseList = new FourPicturesChoose[productInfoList.size()];

        recycleCommonAdapter = new RecycleCommonAdapter<OrderResp.DataBean.ProductBean>(this, productInfoList, R.layout.comment_item) {
            @Override
            public void convert(RecycleCommonViewHolder helper, final OrderResp.DataBean.ProductBean item, int position) {
                helper.setSimpleDraweeView(R.id.sdv_good, item.getPreview());
                helper.setText(R.id.tx_name, item.getTitle());
                RatingBar ratingBar = helper.getView(R.id.ratingbar_quality);
                ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
                    @Override
                    public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                        item.setRating(String.valueOf(rating));
                    }
                });
                SparseArray<ImageView> viewSparseArray;
                viewSparseArray = new SparseArray<>();
                ImageView orderHomerepairImg1 = helper.getView(R.id.order_homerepair_img1);
                ImageView orderHomerepairImg2 = helper.getView(R.id.order_homerepair_img2);
                ImageView orderHomerepairImg3 = helper.getView(R.id.order_homerepair_img3);
                ImageView orderHomerepairImg4 = helper.getView(R.id.order_homerepair_img4);

                viewSparseArray.put(0, orderHomerepairImg1);
                viewSparseArray.put(1, orderHomerepairImg2);
                viewSparseArray.put(2, orderHomerepairImg3);
                viewSparseArray.put(3, orderHomerepairImg4);
                FourPicturesChoose fourPicturesChoose = new FourPicturesChoose(CommentActivity.this, viewSparseArray);
                fourPicturesChooseList[position] = fourPicturesChoose;

                final EditText editText = helper.getView(R.id.edit_comment);
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        String str = editText.getText().toString().trim();
                        item.setComment(str);
                    }
                });
            }
        };
        recycleView.setLayoutManager(new LinearLayoutManager(this));
        recycleView.setAdapter(recycleCommonAdapter);
    }

    @OnClick(R.id.tx_submit)
    public void onClick() {
        HashMap<String, RequestBody> params = new HashMap<>();
        List<MultipartBody.Part> partList = new ArrayList<>();
        for (int i = 0; i < productInfoList.size(); i++) {
            if (!TextUtils.isEmpty(productInfoList.get(i).getComment())) {
                params.put(String.format("content", productInfoList.get(i).getProductid()), RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), productInfoList.get(i).getComment()));
            }
            params.put(String.format("grade-%s", productInfoList.get(i).getProductid()),RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), productInfoList.get(i).getRating()));
            ArrayList<String> strings = fourPicturesChooseList[i].getChosenImageList();
            if (strings.size() > 0) {
                for (int j = 0; j < strings.size(); j++) {
                    try {
                        File imgFile = UImageUtils.sword(strings.get(j));
                        partList.add(MultipartBody.Part.createFormData(String.format("name-%s-%s", productInfoList.get(i).getProductid(), j), String.format("image-%s-%s", productInfoList.get(i).getProductid(), j),
                                RequestBody.create(MediaType.parse("image/png"), imgFile)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        doOrder(params,partList);
    }


    private void doOrder(HashMap<String, RequestBody> params, List<MultipartBody.Part> partList) {
        showLoading();
        enqueue(createCallService(HomeService.class).orderActive(
                RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), SePref.getToken()),
                RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), "comment"),
                RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), orderBean.getOrdersn()),
                params,partList ), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                ToastUtil.show("评价成功");
                finish();
                misLoading();
            }

            @Override
            public void onError(String msg) {
                misLoading();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        for (FourPicturesChoose fourPicturesChoose : fourPicturesChooseList)
            fourPicturesChoose.setImageList(requestCode, resultCode, data);
    }
}
